<template>
  <span>
    <el-button plain
               @click="handleSign">批量签收</el-button>
    <el-dialog title="提示"
               class="dialog-box"
               :visible="visible"
               :close-on-click-modal="false"
               :width="width"
               top="43vh"
               :before-close="handleClose">
      <SignContent :value="result"
                   :selection="value.selection"
                   :stop-loop="stopLoop"
                   :is-footer="isFooter" />
      <!-- <div>
        <template v-if="isFooter">
          <span>{{ content }}</span>
        </template>
        <template v-else>
          <span v-if="!stopLoop"
                class="warning-item">
            <img class="execute-gif"
                 :src="executeGif">
            {{ progressContent }}
          </span>
          <span v-if="stopLoop"
                class="warning-item">
            <img class="warning-img"
                 :src="warning">
            {{ tipContent }}
          </span>
        </template>
      </div> -->
      <span v-if="isFooter"
            slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button :loading="loading"
                   type="primary"
                   @click="handleSubmit">确 定</el-button>
      </span>
      <div v-if="stopLoop"
           slot="footer"
           class="dialog-footer">
        <el-button @click="handleCancel">我知道了</el-button>
      </div>
    </el-dialog>
  </span>
</template>
<script>
import axios from 'axios'
import BatchMixin from '../mixins/batch.mixin'
import SignContent from '../../advance/SignContent.vue';

// function regexId (url) {
//   const regex = /{([^}]+)}/;
//   const [_, key] = url.match(regex) || [];
//   if (!key) {
//     console.log("未找到匹配的ID");
//   }
//   return key;
// }

export default {
  name: "BatchSign",
  components: {
    SignContent
  },
  mixins: [BatchMixin],
  inject: ['$table'],
  props: {
    value: {
      type: Object,
      default: () => { }
    },
    data: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      visible: false,
      stopLoop: false,
      result: {},
      timer: null,
      taskId: null,
      loading: false,
      isFooter: true,
      height: '90px'
    }
  },
  computed: {
    width () {
      return '420px'
    },
    selectionLength () {
      return this.value?.selection?.length || 0
    },
    url () {
      return this.value?.url
    },
    taskUrl () {
      return `/tenant/task/{id}`
    },
    // progressContent () {
    //   const { totalNum, finishedNum, unfinishedNum } = this.result
    //   return `批量签收共${totalNum || this.selectionLength}单，已处理${finishedNum || 0}单，剩余${unfinishedNum || this.selectionLength}单`
    // },
    // tipContent () {
    //   return `正在进行签收批量操作，离开页面后，批量操作结果可点击导航栏-任务中心图标查看。`
    // }
  },
  watch: {
    visible () {
      this.stopLoop = false
      this.isFooter = true
      this.loading = false
      this.taskId = null
      this.result = {}
    }
  },
  created () {
  },
  beforeDestroy () {
    this.$once("hook:beforeDestroy", () => clearInterval(this.timer));
  },
  methods: {
    handleSign () {
      if (!this.selectionLength) {
        return this.$message.warning("请至少选择一条数据")
      }
      this.visible = true
    },
    handleClose () {
      if (this.stopLoop) {
        this.visible = false;
        this.$table.search();
        return;
      }
      if (this.taskId) {
        this.stopLoop = true;
        return;
      }
      if (this.loading) {
        this.$message.warning('批量签收正在进行中');
        return;
      }
      this.visible = false;
    },
    handleCancel () {
      this.timer = setTimeout(() => {
        this.stopLoop = true
        this.isFooter = false
      }, 0);
      this.visible = false
      this.$table.search();
    },
    async handleSubmit () {
      this.loading = true
      const response = await this.sign()
      if (response) {
        this.isFooter = false
        this.procedure(this.taskUrl, response)
        return
      }
    },
    async sign () {
      try {
        let response = await axios.post(this.url, this.data)
        if (response?.code === 0) {
          this.taskId = response?.data;
          if (!response?.data) {
            this.visible = false
            this.loading = false
            this.$table.search();
          }
          return response?.data;
        } else {
          this.loading = false;
          this.$message({ type: "error", message: response?.message });
        }
      } catch (error) {
        this.loading = false;
      }
    },
    // async procedure (taskUrl, id) {
    //   // this.loading = true
    //   const response = await this.loopUntilProgressIsOne(taskUrl, id)
    //   this.result = response
    //   if (this.result.progress === 1) {
    //     this.visible = false;
    //     // this.loading = false
    //     this.$message({ type: "success", message: "操作成功" });
    //     this.$table.search();
    //   }
    // },
    // async fetchBatchId (url, id) {
    //   const key = regexId(url);
    //   const apiUrl = url.replace(`{${key}}`, id);
    //   try {
    //     const response = await axios.get(apiUrl);
    //     return response.data;
    //   } catch (error) {
    //     console.error(error);
    //     throw error;
    //   }
    // },
    // async loopUntilProgressIsOne (taskUrl, id) {
    //   let result;
    //   const interval = 3000; // 调用接口的时间间隔，单位为毫秒
    //   do {
    //     try {
    //       result = await this.fetchBatchId(taskUrl, id);
    //       await new Promise(resolve => setTimeout(resolve, interval)); // 等待一段时间后再继续调用接口
    //       this.$set(this, 'result', result);
    //     } catch (error) {
    //       console.error('批量任务进程异常' + error);
    //       break;
    //     }
    //   } while (result.progress !== 1 && !this.stopLoop);

    //   return result;
    // },
  },
}
</script>

<style scoped>
/* 15px 15px 10px  5px 15px 0     10px 15px */
.dialog-box >>> .el-dialog__header {
  padding: 10px 15px 10px;
  background: #ffffff;
}
.dialog-box >>> .el-dialog__headerbtn {
  top: 14px;
}
.dialog-box {
  text-align: left;
}

.dialog-box >>> .el-dialog__body {
  padding: 10px 15px;
  /* font-size: 16pc; */
}
.dialog-box >>> .el-dialog__footer {
  padding: 5px 15px 10px;
}

.dialog-footer {
  text-align: right;
}
</style>